﻿using System;
using System.Collections.Generic;
using System.Data.Objects;
using System.Data.Objects.DataClasses;
using System.Linq;
using System.Linq.Expressions;
using System.Web;
using Yeap.Kernel.Unity;

namespace Yeap.Kernel.Storage
{
    public class RepositoryBase<T> : IRepository<T> where T:EntityObject, new()
    {
        protected YeapDbEntities context;
        protected ObjectSet<T> query;

        public RepositoryBase()
        {
            context = new YeapDbEntities();
            query = context.CreateObjectSet<T>();
        }

        #region [Implementation of IRepository<T>]
        
        public T GetById(int id)
        {
            return query.AsEnumerable().Where(p => (int)p.EntityKey.EntityKeyValues[0].Value == id).FirstOrDefault();
        }

        public IEnumerable<T> GetAll()
        {
            return query;
        }

        public IEnumerable<T> Query(Expression<Func<T, bool > > filter)
        {
            return query.Where(filter);
        }

        public void Add(T obj)
        {
            query.AddObject(obj);
            context.SaveChanges();
        }

        public void Update ()
        {
            context.SaveChanges();
        }

        #endregion



    }
}